package com.lyl.servicelive.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyl.commonutils.DateUtils;
import com.lyl.commonutils.R;
import com.lyl.exception.ZxjyException;
import com.lyl.servicelive.cloudclient.EduClient;
import com.lyl.servicelive.entity.Course;
import com.lyl.servicelive.entity.CourseAccount;
import com.lyl.servicelive.entity.CourseDescription;
import com.lyl.servicelive.entity.Visitor;
import com.lyl.servicelive.entity.vo.LiveCourseApiFormVo;
import com.lyl.servicelive.entity.vo.LiveCourseFormVo;
import com.lyl.servicelive.entity.vo.LiveCourseVo;
import com.lyl.servicelive.mapper.CourseMapper;
import com.lyl.servicelive.mtcloud.CommonResult;
import com.lyl.servicelive.mtcloud.MTCloud;
import com.lyl.servicelive.service.CourseAccountService;
import com.lyl.servicelive.service.CourseDescriptionService;
import com.lyl.servicelive.service.CourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyl.servicelive.service.VisitorService;
import lombok.SneakyThrows;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 直播课程表 服务实现类
 * </p>
 *
 * @author 雷艳玲
 * @since 2022-07-05
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    EduClient eduClient;

    @Autowired
    private CourseAccountService courseAccountService;

    @Autowired
    private CourseDescriptionService courseDescriptionService;

    @Resource
    private MTCloud mtCloudClient;

    @Autowired
    VisitorService visitorService;


    @SneakyThrows// lombok抛出异常
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public boolean save(LiveCourseFormVo liveCourseFormVo) {
        Course liveCourse = new Course();
        BeanUtils.copyProperties(liveCourseFormVo, liveCourse);

        R teacherR = eduClient.getById(liveCourse.getTeacherId());

        Map teacherMap = JSON.parseObject(JSON.toJSONString(teacherR.getData().get("item")), Map.class);


        HashMap<Object, Object> options = new HashMap<>();
        options.put("scenes", 2);//直播类型。1: 教育直播，2: 生活直播。默认 1，说明：根据平台开通的直播类型填写
        options.put("password", liveCourseFormVo.getPassword());
        System.out.println("直播配置:" + liveCourse);
        String res = mtCloudClient.courseAdd(
                liveCourse.getCourseName(),
                liveCourse.getTeacherId().toString(),
                DateUtils.formatDateTime(liveCourse.getStartTime()),
                DateUtils.formatDateTime(liveCourse.getEndTime()),
                (String)teacherMap.get("name"),
                (String)teacherMap.get("career"), options);

        System.out.println("return:: "+res);
        CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
        if(Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {
            JSONObject object = commonResult.getData();
            liveCourse.setCourseId(object.getLong("course_id"));
            baseMapper.insert(liveCourse);

            //保存课程详情信息
            CourseDescription courseDescription = new CourseDescription();
            courseDescription.setDescription(liveCourseFormVo.getDescription());
            courseDescription.setLiveCourseId(liveCourse.getId());
            courseDescriptionService.save(courseDescription);

            //保存课程账号信息
            CourseAccount liveCourseAccount = new CourseAccount();
            liveCourseAccount.setLiveCourseId(liveCourse.getId());
            liveCourseAccount.setZhuboAccount(object.getString("bid"));
            liveCourseAccount.setZhuboPassword(liveCourseFormVo.getPassword());
            liveCourseAccount.setAdminKey(object.getString("admin_key"));
            liveCourseAccount.setUserKey(object.getString("user_key"));
            liveCourseAccount.setZhuboKey(object.getString("zhubo_key"));
            courseAccountService.save(liveCourseAccount);
        } else {
            String getmsg = commonResult.getmsg();
            throw new ZxjyException(20001,getmsg);
        }
        return true;
    }

    @Override
    public boolean removeLive(Long id) {
        //根据id查询直播课程信息
        Course liveCourse = baseMapper.selectById(id);
        if(liveCourse != null) {
            //获取直播courseid
            Long courseId = liveCourse.getCourseId();
            try {
                //调用方法删除平台直播课程
                mtCloudClient.courseDelete(courseId.toString());
                //删除表数据
                baseMapper.deleteById(id);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                throw new ZxjyException(20001,"删除直播课程失败");
            }
        }
        return false;
    }


    @Override
    public LiveCourseFormVo getLiveCourseFormVo(Long id) {
        Course liveCourse = this.getById(id);
        CourseDescription liveCourseDescription =courseDescriptionService.getLiveCourseById(id);

        LiveCourseFormVo liveCourseFormVo = new LiveCourseFormVo();
        BeanUtils.copyProperties(liveCourse, liveCourseFormVo);
        liveCourseFormVo.setDescription(liveCourseDescription.getDescription());
        return liveCourseFormVo;
    }

    //更新
    @Override
    public boolean updateById(LiveCourseFormVo liveCourseFormVo) {
        //根据id获取直播课程基本信息
        Course liveCourse = baseMapper.selectById(liveCourseFormVo.getId());
        BeanUtils.copyProperties(liveCourseFormVo,liveCourse);
        //讲师
        R teacherR = eduClient.getById(liveCourse.getTeacherId());
        Map teacherMap = JSON.parseObject(JSON.toJSONString(teacherR.getData().get("item")), Map.class);

        liveCourse.setTeacherCareer((String)teacherMap.get("career"));
        liveCourse.setTeacherName((String)teacherMap.get("name"));
//             *   course_id 课程ID
//     *   account 发起直播课程的主播账号
//     *   course_name 课程名称
//     *   start_time 课程开始时间,格式:2015-01-01 12:00:00
//                *   end_time 课程结束时间,格式:2015-01-01 13:00:00
//                *   nickname 	主播的昵称
//                *   accountIntro 	主播的简介
//                *  options 		可选参数
        HashMap<Object, Object> options = new HashMap<>();
        System.out.println("修改:" +liveCourse);
        try {
            String res = mtCloudClient.courseUpdate(
                    liveCourse.getCourseId().toString(),
                    liveCourseFormVo.getTeacherId().toString(),
                    liveCourse.getCourseName(),
                    DateUtils.formatDateTime(liveCourse.getStartTime()),
                    DateUtils.formatDateTime(liveCourse.getEndTime()),
                    liveCourse.getTeacherName(),
                    liveCourse.getTeacherCareer(),
                    options);

            System.out.println("res:"+res);
            //返回结果转换，判断是否成功
            CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
            if(Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {
                JSONObject object = commonResult.getData();
                //更新直播课程基本信息
                liveCourse.setCourseId(object.getLong("course_id"));
                baseMapper.updateById(liveCourse);
                //直播课程描述信息更新
                CourseDescription liveCourseDescription =
                        courseDescriptionService.getLiveCourseById(liveCourse.getId());
                liveCourseDescription.setDescription(liveCourseFormVo.getDescription());
                courseDescriptionService.updateById(liveCourseDescription);

                return true;
            } else {
                throw new ZxjyException(20001,"修改直播课程失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  false;
    }

    @Override
    public List<LiveCourseVo> findLatelyList() {
        List<LiveCourseVo> liveCourseVoList = baseMapper.findLatelyList();

        for(LiveCourseVo liveCourseVo : liveCourseVoList) {
            liveCourseVo.setStartTimeString(DateUtils.formatDateTime(liveCourseVo.getStartTime()));
            liveCourseVo.setEndTimeString(DateUtils.formatDateTimeHm(liveCourseVo.getEndTime()));

            Long teacherId = liveCourseVo.getTeacherId();

            R teacherR = eduClient.getById(teacherId);

            Map teacherMap = JSON.parseObject(JSON.toJSONString(teacherR.getData().get("item")), Map.class);

            liveCourseVo.setTeacherName((String)teacherMap.get("name"));
            liveCourseVo.setTeacherCareer((String)teacherMap.get("career"));


            liveCourseVo.setLiveStatus(this.getLiveStatus(liveCourseVo));
        }
        return liveCourseVoList;
    }

    @Override
    public Map<String, Object> pageListWeb(Page<Course> pageParam) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(true,"start_time");
        queryWrapper.orderByDesc(true,"id");
        baseMapper.selectPage(pageParam, queryWrapper);

//        List<LiveCourseApiFormVo> records = pageParam.getRecords();
        List<Course> records = pageParam.getRecords();


        List<LiveCourseApiFormVo> datas= new ArrayList<>();
        records.forEach(item->{
            LiveCourseApiFormVo liveCourseApiFormVo= new LiveCourseApiFormVo();

            R r=  eduClient.getById(item.getTeacherId());// 根据讲师id 获取讲师
            Map<String,Object> map = JSON.parseObject(JSON.toJSONString(r.getData().get("item")), Map.class);


            CourseDescription description = courseDescriptionService.getLiveCourseById(item.getId());
            BeanUtils.copyProperties(item,liveCourseApiFormVo);
            // 播放路径
            liveCourseApiFormVo.setTeacherName((String)map.get("name"));
            liveCourseApiFormVo.setAvatar((String)map.get("avatar"));
            liveCourseApiFormVo.setUrl("https://live.zhibodun.com/live/courseLogin.php?course_id="+item.getCourseId());
            liveCourseApiFormVo.setDescription(description.getDescription());
            datas.add(liveCourseApiFormVo);
            System.out.println(liveCourseApiFormVo);
        });

        long current = pageParam.getCurrent();//当前页
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", datas);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        return  map;
    }


    /**
     * 直播状态 0：未开始 1：直播中 2：直播结束
     * @param liveCourse
     * @return
     */
    private int getLiveStatus(Course liveCourse) {
        // 直播状态 0：未开始 1：直播中 2：直播结束
        int liveStatus = 0;
        Date curTime = new Date();
        // 7:30 ~ 8:30
        // 当前时间 - 开始时间
        long start = curTime.getTime() - liveCourse.getStartTime().getTime() ;
        //  当前时间 - 结束时间
        long end = curTime.getTime() - liveCourse.getEndTime().getTime() ;


        if (start < 0) {
            liveStatus = 0;// 未开始
        } else if (end > 0 ) {
            liveStatus = 2;
        } else {
            liveStatus = 1;// 直播中
        }
        return liveStatus;
    }

    //直播课程分页查询
    @Override
    public IPage<Course> selectPage(Page<Course> pageParam) {
        IPage<Course> page = baseMapper.selectPage(pageParam, null);

        List<Course> liveCourseList = page.getRecords();

        List<Course> finalData=new ArrayList<>();

        for(Course liveCourse : liveCourseList) {

            R teacherR = eduClient.getById(liveCourse.getTeacherId());

            Map map = JSON.parseObject(JSON.toJSONString(teacherR.getData().get("item")), Map.class);

            liveCourse.setTeacherName( (String)map.get("name"));
            liveCourse.setTeacherCareer((String)map.get("career"));
        }
        return page;
    }


}
